// 显示加载中提示
function showLoading(message) {
    // 创建加载提示元素
    var loading = $('<div class="loading-overlay"><div class="loading-spinner"></div><div class="loading-message">' + message + '</div></div>');
    
    // 添加到页面
    $('body').append(loading);
}

// 隐藏加载中提示
function hideLoading() {
    $('.loading-overlay').remove();
}

// 显示提示消息
function showMessage(message, type) {
    // 创建提示元素
    var alert = $('<div class="alert alert-' + type + ' alert-dismissible fade show" role="alert">' +
                 message +
                 '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>' +
                 '</div>');
    
    // 添加到页面
    $('.container').prepend(alert);
    
    // 3秒后自动关闭
    setTimeout(function() {
        alert.alert('close');
    }, 3000);
}

// 格式化日期
function formatDate(dateString) {
    var date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    });
}

// 添加CSS样式
$('<style>')
    .text(`
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(255, 255, 255, 0.8);
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            z-index: 9999;
        }
        .loading-spinner {
            width: 40px;
            height: 40px;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #3498db;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        .loading-message {
            margin-top: 10px;
            color: #666;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    `)
    .appendTo('head');

// 配置管理器
const ConfigManager = {
    // 加载配置
    loadConfig() {
        try {
            const token = localStorage.getItem('wechat_token');
            const cookie = localStorage.getItem('wechat_cookie');
            const fakeid = localStorage.getItem('wechat_fakeid');

            if (token) $('#token').val(token);
            if (cookie) $('#cookie').val(cookie);
            if (fakeid) $('#fakeid').val(fakeid);

            console.log('配置加载成功');
        } catch (error) {
            console.error('加载配置失败:', error);
            showMessage('加载配置失败', 'danger');
        }
    },

    // 保存配置
    saveConfig() {
        try {
            const token = $('#token').val();
            const cookie = $('#cookie').val();
            const fakeid = $('#fakeid').val();

            localStorage.setItem('wechat_token', token);
            localStorage.setItem('wechat_cookie', cookie);
            localStorage.setItem('wechat_fakeid', fakeid);

            console.log('配置保存成功');
            showMessage('配置保存成功', 'success');
        } catch (error) {
            console.error('保存配置失败:', error);
            showMessage('保存配置失败', 'danger');
        }
    },

    // 清除配置
    clearConfig() {
        try {
            localStorage.removeItem('wechat_token');
            localStorage.removeItem('wechat_cookie');
            localStorage.removeItem('wechat_fakeid');

            $('#token').val('');
            $('#cookie').val('');
            $('#fakeid').val('');

            console.log('配置清除成功');
            showMessage('配置清除成功', 'success');
        } catch (error) {
            console.error('清除配置失败:', error);
            showMessage('清除配置失败', 'danger');
        }
    }
};

// 显示消息提示
function showMessage(message, type = 'info') {
    const alertHtml = `
        <div class="alert alert-${type} alert-dismissible fade show" role="alert">
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    `;
    $('#message-container').html(alertHtml);
}

// 显示加载动画
function showLoading(message = '处理中...') {
    $('.loading').html(`
        <div class="d-flex justify-content-center">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">${message}</span>
            </div>
        </div>
    `).show();
}

// 隐藏加载动画
function hideLoading() {
    $('.loading').hide();
}

// 页面加载完成后执行
$(document).ready(function() {
    // 加载配置
    ConfigManager.loadConfig();

    // 绑定保存配置按钮事件
    $('#save-config').click(function() {
        ConfigManager.saveConfig();
    });

    // 绑定清除配置按钮事件
    $('#clear-config').click(function() {
        ConfigManager.clearConfig();
    });

    // 绑定采集文章表单提交事件
    $('#collect-form').submit(function(e) {
        e.preventDefault();
        showLoading();

        const formData = {
            token: $('#token').val(),
            cookie: $('#cookie').val(),
            fakeid: $('#fakeid').val()
        };

        $.ajax({
            url: '/api/articles/collect',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(formData),
            success: function(response) {
                if (response.code === 0) {
                    showMessage('文章采集成功', 'success');
                    setTimeout(() => window.location.reload(), 1500);
                } else {
                    showMessage(response.message || '文章采集失败', 'danger');
                }
            },
            error: function(xhr) {
                showMessage(xhr.responseJSON?.message || '服务器错误', 'danger');
            },
            complete: function() {
                hideLoading();
            }
        });
    });
});

// 更新文章列表
function updateArticleList(articles) {
    const tbody = document.querySelector('table tbody');
    tbody.innerHTML = '';
    
    articles.forEach(article => {
        const tr = document.createElement('tr');
        tr.innerHTML = `
            <td>${article.title}</td>
            <td>${article.author}</td>
            <td>${new Date(article.create_time).toLocaleString()}</td>
            <td>
                <a href="/preview/${article.id}" class="btn btn-sm btn-info">预览</a>
            </td>
        `;
        tbody.appendChild(tr);
    });
}

// 处理表单提交
document.getElementById('collect-form').addEventListener('submit', async function(e) {
    e.preventDefault();
    
    const formData = {
        token: document.getElementById('token').value,
        cookie: document.getElementById('cookie').value,
        fakeid: document.getElementById('fakeid').value
    };
    
    if (!formData.token || !formData.cookie || !formData.fakeid) {
        showMessage('请填写完整信息', 'danger');
        return;
    }
    
    try {
        showLoading();
        showMessage('开始采集文章...', 'info');
        
        const response = await fetch('/api/articles/collect', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(formData)
        });
        
        const data = await response.json();
        
        if (response.ok) {
            showMessage('采集成功！');
            // 更新文章列表
            updateArticleList(data.articles);
        } else {
            showMessage(data.error || '采集失败', 'danger');
        }
    } catch (error) {
        showMessage('采集失败: ' + error.message, 'danger');
    } finally {
        hideLoading();
    }
});

// 生成PDF函数
function generatePDF(articleId) {
    console.log('开始生成PDF，文章ID:', articleId);
    const btn = $(`.generate-pdf[onclick*="${articleId}"]`);
    console.log('找到按钮:', btn.length > 0);
    
    if (btn.length === 0) {
        console.error('未找到对应的按钮');
        return;
    }
    
    btn.prop('disabled', true);
    btn.html('<i class="fas fa-spinner fa-spin"></i> 生成中...');
    
    $.ajax({
        url: `/api/generate-pdf/${articleId}`,
        method: 'POST',
        success: function(response) {
            console.log('PDF生成响应:', response);
            if (response.code === 0) {
                showMessage('PDF生成成功！', 'success');
                setTimeout(() => window.location.reload(), 1500);
            } else {
                showMessage(response.message || '生成PDF失败', 'danger');
                btn.prop('disabled', false);
                btn.html('<i class="fas fa-file-pdf"></i> 生成PDF');
            }
        },
        error: function(xhr, status, error) {
            console.error('PDF生成错误:', {xhr, status, error});
            showMessage(xhr.responseJSON?.message || '服务器错误', 'danger');
            btn.prop('disabled', false);
            btn.html('<i class="fas fa-file-pdf"></i> 生成PDF');
        }
    });
} 